package com.zhixi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixi.common.SharedVariablesCurrent;
import com.zhixi.dto.DishDto;
import com.zhixi.pojo.Dish;
import com.zhixi.pojo.DishFlavor;
import com.zhixi.service.CategoryService;
import com.zhixi.service.DishFlavorService;
import com.zhixi.service.DishService;
import com.zhixi.mapper.DishMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhangzhixi
 * @description 针对表【dish(菜品管理)】的数据库操作Service实现
 * @createDate 2022-07-10 15:59:29
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveDishFlavor(DishDto dishDto, HttpServletRequest request) {
        // 保存菜品
        this.save(dishDto);

        // 拿到菜品的id，然后保存菜品的口味
        Long dishId = dishDto.getId();

        List<DishFlavor> dishFlavors = dishDto.getFlavors();
        dishFlavors = dishFlavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        // 保存菜品的口味
        dishFlavorService.saveBatch(dishFlavors);

        // 清理该分类商品的数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
    }

    @Override
    public Page<Dish> page(int page, int pageSize, String name) {
        log.info("page = {}, pageSize = {} ,name={}", page, pageSize, name);


        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.like(name != null, Dish::getName, name);
        dishQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        Page<Dish> dishPage = this.page(pageInfo, dishQueryWrapper);

        List<Dish> records = dishPage.getRecords();
        // 拿到菜品到的类别名称,并赋值到菜品表中去，等同于下面注释的代码，item存在的时候，才去查询类别名称
        records.forEach(item -> Optional.ofNullable(categoryService.getById(item.getCategoryId())).ifPresent(value -> item.setCategoryName(value.getName())));

        /*for (Dish dish : records) {
            Category serviceById = categoryService.getById(dish.getCategoryId());
            String cateName = serviceById.getName();
            dish.setCategoryName(cateName);
        }*/
        return dishPage;
    }

    @Override
    public DishDto getDishWithFlavor(Long id) {
        // 创建最后要返回的DTO对象
        DishDto dishDto = new DishDto();

        // 查询菜品
        Dish dish = this.getById(id);

        // 查询口味
        LambdaQueryWrapper<DishFlavor> dishFlavorsQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorsQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavorList = dishFlavorService.list(dishFlavorsQueryWrapper);

        // 拷贝查询到的菜品信息到DTO中
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(flavorList);

        return dishDto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWithFlavor(DishDto dishDto, HttpServletRequest request) {
        /*更新菜品*/
        dishService.updateById(dishDto);

        /*清空关于当前菜品的口味信息(根据菜品的ID进行清除)*/
        LambdaQueryWrapper<DishFlavor> dishFlavorQuery = new LambdaQueryWrapper<>();
        dishFlavorQuery.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(dishFlavorQuery);

        /*设置口味的dishId*/
        List<DishFlavor> dishDtoFlavors = dishDto.getFlavors();
        dishDtoFlavors = dishDtoFlavors.stream().peek((item) -> item.setDishId(dishDto.getId())).collect(Collectors.toList());

        /*更新口味信息*/
        dishFlavorService.saveBatch(dishDtoFlavors);

        // 清理该分类商品的数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
    }

    @Override
    public void updateStatus(Long[] id, int i, HttpServletRequest request) {
        List<Dish> dishes = new ArrayList<>();
        for (Long aLong : id) {
            Dish dish = new Dish();
            dish.setId(aLong);
            dish.setStatus(i);
            dishes.add(dish);
        }
        this.updateBatchById(dishes);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatch(List<Long> asList) {
        // 1、根据菜品ID查询出菜品分类
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Dish::getId, asList);

        List<Dish> dishList = dishService.list(lambdaQueryWrapper);
        // 2、删除在redis中存在的该菜品类别的缓存
        dishList.forEach(item -> {
            // 清理该分类商品的数据
            String key = "dish_" + item.getCategoryId() + "_1";
            log.info("要删除的key是{}", key);
            redisTemplate.delete(key);
        });

        // 3、删除菜品
        dishService.removeByIds(asList);
    }
}




